<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>async与await结合发送AJAX请求</title>
</head>

<body>
  <script>
    // 发送 AJAX 请求
    function sendAJAX(url) {
      return new Promise((resolve, reject) => {
        // 1.创建对象
        const xhr = new XMLHttpRequest();

        // 2. 初始化
        xhr.open('get', url);

        // 3. 发送
        xhr.send();

        // 4. 事件绑定
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status === 200 && xhr.status < 300) {
              resolve(xhr.response)
            } else {
              reject(xhr.status)
            }
          }
        }
      })
    }

    /* // promise then方法测试
    sendAJAX('https://api.apiopen.top/getJoke').then(value => {
      console.log(value)
    }, reason => { }) */

    // async 与 await 测试
    async function main() {
      let result = await sendAJAX('https://api.apiopen.top/getJoke');
      console.log(result);

      let tianqi = await sendAJAX('https://tianqiapi.com/api/?version=v1&city=深圳&appid=23941491&appsecret=TXoD5e8P')
      console.log(tianqi)

      let result2 = await sendAJAX('https://v0.yiketianqi.com/aqi/rankcity?appid=23941491&appsecret=TXoD5e8P')
      console.log(result2)
    }
    main()
  </script>
</body>

</html>